//pages/exam/exam.js
const common = require("../../../utils/zstz.js");
//获取应用实例
const app = getApp().globalData;
//获取app.js中的全局变量
let meResult = null,
  otherResult = null,
  showOther = false,
  error = false;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    name: common.name,
    avatar: common.avatar,
    score: '',
    sumScore: 0,
    otherName: '',
    otherAvatar: '',
    otherScore: '',
    otherAnswer: '',
    otherSumScore: 0,
    nextData: '', //下一题的数据，对象
    timer: '', //定时器名字
    timer2: '', //3秒间隔定时器
    delayTimer: '', //动效延迟的定时器
    countDownNum: 10, //设置倒计时初始值
    rotateLeft: 'rotateLeft',
    rotateRight: 'rotateRight',
    index: 1, //题目的索引
    selectClass: '', //点击了答案的状态
    selfClass: '', //选中答案对错状态显示
    correctClass: '', //正确答案的状态显示
    otherClickId: '', //对方选中的答案下标
    otherClass: '', //对方的答案样式
    titleMove: 'titleMove', //标题出现动效类名
    titleNoMove: 'titleNoMove', //标题题号出现动效类名
    answersMove: 'answersMove', //答案出现动效类名
    circleMove: 'circleMove', //计时器的动效类名
    title: '', //本次显示的标题
    answer: [], //本次显示的答案
    correctId: '', //本次正确的答案
    clickId: 0, //点击答案的下标
    addScore: '', //答题得分
    otherScore: '', //对方答题得分
    matchType: '',
    qCataId: '',
    cataname: '',
    alreadyClick: false, //记录已经点击过了
    hide: 'hide' //控制如果是空答案就隐藏
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this,
      token = wx.getStorageSync('token'),
      openId = wx.getStorageSync('openid');
    let wsUrl = common.wsUrl + 'gaming/' + openId;
    that.setData({
      countDownNum: app.countDownNum,
      otherName: options.name,
      otherAvatar: options.avatar,
      matchType: options.matchType,
      qCataId: options.qCataId,
      cataname: options.cataname,
      name: wx.getStorageSync('userInfo').nickName,
      avatar: wx.getStorageSync('userInfo').avatarUrl
    });
    //动态修改标题
    wx.setNavigationBarTitle({
      title: options.cataname
    })
    //连接上链接
    that.connect(wsUrl);
    //监听连接成功
    wx.onSocketOpen(function () {
      that.send("getQ", that.data.index, ''); //这里是第一题
    })
    //监听服务器向前端发送数据
    wx.onSocketMessage(function (res) {
      var result = JSON.parse(res.data);
      console.log(result)
      //getQ指令，说明是拿到下一题的信息,执行渲染逻辑，执行定时器定时
      if (result.func == "GetQ") {
        that.GetQ(result.data);
      }
      //endQ指令 渲染自己的答案
      if (result.func == "renderMeScore") {
        meResult = result;
        if (otherResult != null) {
          //同时渲染
          console.log('同时渲染');
          that.renderMeScore(result);
          that.renderOtherOnlyScore(result) //首先渲染积分
          that.renderOtherScore(otherResult);
          clearInterval(that.data.timer);
          that.setData({
            rotateLeft: '',
            rotateRight: '',
          })
          that.send('overQ', that.data.index, '') //请求下一题
        } else {
          that.renderMeScore(result);
        }
      }
      //endQ指令 渲染对方的答案
      if (result.func == "renderOtherScore") {
        that.renderOtherOnlyScore(result) //首先渲染积分
        console.log('---->>', that.data.index, result.q_num);
        if (that.data.index < result.q_num) { //自己题号落后
          that.setData({
            index: result.q_num
          });
        } else if (that.data.index == result.q_num) { //题号相同
          if (meResult == null) {
            //自己没答完
            otherResult = result;
            showOther = true;
          } else {
            console.log('渲染他的', otherResult);
            that.renderOtherScore(result);
            clearInterval(that.data.timer);
            that.setData({
              rotateLeft: '',
              rotateRight: '',
            })
            that.send('overQ', that.data.index, '') //请求下一题
          }
        } else { //自己题号超前
          if (meResult != null) {
            clearInterval(that.data.timer);
            that.setData({
              rotateLeft: '',
              rotateRight: '',
            });
            that.send('overQ', that.data.index, '') //请求下一题
          }
        }
      }
      //overQ 指令 渲染正确答案
      if (result.func == "OverQ") {
        that.OverQ(result.data);
      }
      //endPK指令 pk结束跳转页面 传参数 渲染数据
      if (result.func == "renderFinalScore") {
        setTimeout(() => {
          that.reanderFinalScore(result);
        }, 1500)

      }
    });
    //监听链接关闭
    wx.onSocketClose(function (res) {
      //说明是意外断网，导致连接关闭，跳转网络异常页面
      if (error) {
        console.log('网络异常关闭链接' + error);
        wx.redirectTo({
          url: '../error/error',
        })
      } else {
        error = false;
        console.log('手动关闭链接' + error);
      }
    });
  },

  //打开连接
  connect(url) {
    wx.connectSocket({
      url: url,
      data: {},
      method: 'get',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {},
      fail: function () {},
    });
  },

  cancel() {
    //关闭长连接
    wx.closeSocket(function (res) {
      error = true;
      console.log('手动关闭链接' + error)
    });
  },

  //发送数据函数
  send(cmd, num, answer) {
    let data = {
      token: wx.getStorageSync('token'),
      cmd: cmd,
      openId: wx.getStorageSync('openid'),
      q_num: num,
      answer: answer,
    };
    if (cmd == 'endQ') {
      console.log('发送答案题号：' + data.q_num + '发送答案：' + data.answer)
    }
    wx.sendSocketMessage({
      data: JSON.stringify(data),
      success: (res) => {
        console.log('发送消息成功->' + cmd)
      },
      fail: () => {},
    })
    //监听链接打开成功，然后可以做前端向服务器发送信息
  },

  //10秒倒计时定时器 发送overQ指令
  countDown: function () {
    let that = this;
    let countDownNum = that.data.countDownNum; //获取倒计时初始值
    that.data.timer = setInterval(function () { //这里把setInterval赋值给变量名为timer的变量
      if (countDownNum == 0) {
        //10秒时间到 发动overQ 显示下一题
        that.send('overQ', that.data.index, '') //请求下一题
        clearInterval(that.data.timer);
      } else {
        countDownNum--;
        that.setData({
          countDownNum: countDownNum
        });
      }
    }, 1000)
  },

  //点击选中答案
  clickAnswer: function (event) {
    let that = this,
      index = event.currentTarget.dataset.index,
      answer; //获取当前点击的元素下标志
    if (that.data.alreadyClick) {
      return;
    }
    if (index == 0) {
      answer = 'A'
    }
    if (index == 1) {
      answer = 'B'
    }
    if (index == 2) {
      answer = 'C'
    }
    if (index == 3) {
      answer = 'D'
    }
    that.setData({
      clickId: index,
      selectClass: 'select',
      alreadyClick: true
    });
    that.send('endQ', that.data.index, answer); //发送答题结束服务器开始记录时间，传参答案
  },

  //当前用户题目的结果
  renderMeScore(data) {
    let that = this;
    that.setData({
      score: data.score,
      sumScore: data.sumScore,
    });
    if (data.score == 0) {
      //答错了
      that.setData({
        selfClass: 'false left',
        selectClass: ''
      })
    } else {
      that.setData({
        selfClass: 'true left',
        selectClass: ''
      })
    }
  },

  //对方用户渲染积分
  renderOtherOnlyScore(data) {
    let that = this;
    that.setData({
      otherScore: data.otherScore,
      otherSumScore: data.otherSumScore
    });
  },

  //对方用户题目结果
  renderOtherScore(data) {
    let that = this,
      otherClickId;
    if (data.otherAnswer == 'A') {
      otherClickId = 0
    }
    if (data.otherAnswer == 'B') {
      otherClickId = 1
    }
    if (data.otherAnswer == 'C') {
      otherClickId = 2
    }
    if (data.otherAnswer == 'D') {
      otherClickId = 3
    }
    that.setData({
      otherClickId: otherClickId,
    });
    if (data.otherScore == 0) {
      //答错了
      that.setData({
        otherClass: 'false right',
        selectClass: ''
      });
    } else {
      that.setData({
        otherClass: 'true right',
        selectClass: ''
      })
    }
  },

  //请求下一题的逻辑
  GetQ(data) {
    let that = this;
    clearInterval(that.data.timer);
    clearInterval(that.data.timer2);
    meResult = null;
    otherResult = null;
    showOther = false;
    //动效慢慢出现
    that.setData({
      rotateLeft: 'rotateLeft',
      rotateRight: 'rotateRight',
      titleMove: 'titleMove',
      titleNoMove: 'titleNoMove',
      answersMove: 'answersMove',
      circleMove: 'circleMove',
      title: data.quesetion,
      answer: [data.optionA, data.optionB, data.optionC, data.optionD],
      countDownNum: app.countDownNum,
    });
    setTimeout(() => {
      that.setData({
        alreadyClick: false,
      })
    }, 1000) //延迟一秒执行  防止题没有出来就选上答案
    that.send('startQ', that.data.index, ''); //发送答题开始服务器开始记录时间
    that.countDown(); //执行定时器
  },

  //overQ指令的逻辑，显示正确答案,题目索引加1，隔两秒重新发请求下一题，如果索引超过10 就发指令endPk 
  OverQ(res) {
    let that = this,
      answerIndex, data = res.replace(/\s+/g, '');
    //显示正确答案
    if (data == 'D') {
      answerIndex = 3
    }
    if (data == 'C') {
      answerIndex = 2
    }
    if (data == 'B') {
      answerIndex = 1
    }
    if (data == 'A') {
      answerIndex = 0
    }
    that.setData({
      correctId: answerIndex,
      correctClass: 'true',
      alreadyClick: true
    });
    //对方比我先答 ,我后答，就最后和正确答案一起显示
    if (showOther) {
      that.renderOtherScore(otherResult);
    }
    let currIndex = that.data.index + 1; //题目索引加1
    if (currIndex > common.subjectSum) {
      //pk结束  调用
      clearInterval(that.data.timer);
      that.send('endPK', common.subjectSum, '') //五道题结束，发送pk结束指令
    } else {
      //显示正确答案1秒之后开始请求下一题
      that.data.timer2 = setTimeout(() => {
        that.setData({
          selfClass: '', //每换一题所有答案状态清空
          correctClass: '',
          selectClass: '',
          otherClass: '',
          rotateLeft: '',
          rotateRight: '',
          titleMove: '',
          titleNoMove: '',
          answersMove: '',
          circleMove: '',
        })
        that.setData({
          index: currIndex //题目索引赋值
        });
        that.send('getQ', that.data.index, '') //请求下一题
      }, 2000)
    }
  },

  //pk结束
  reanderFinalScore(data) {
    let that = this;
    //关闭长连接
    that.cancel();
    //清空定时器
    clearInterval(that.data.timer);
    //隔两秒挑转到pk结束页
    wx.redirectTo({
      url: '../challResult/challResult?matchType=' + that.data.matchType + '&qCataId=' + that.data.qCataId + '&cataname=' + that.data.cataname + '&meScore=' + data.meScore + '&otherScore=' + data.otherScore + '&finalScore=' + data.finalScore + '&name=' + that.data.otherName + '&avatar=' + that.data.otherAvatar
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //关闭长连接
    this.cancel();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
  
})